<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .imgContainer{
            width: 400px;
            height: 400px;
            background-color: gray;
        }
    </style>
</head>
<body>
    <div class="imgContainer"></div>
    <button>按钮</button>
    <script>
        var imgArr = ["https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F4k%2Fs%2F02%2F2109242326224L3-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1647655526&t=593ff3059c8c461d5cfa25ea30235515","https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1113%2F060120105F7%2F200601105F7-1-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1647655526&t=38a6f0c02d49bb17021b5bdca8cbcdf6","https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2F26%2Fc8%2F69%2F26c869bc8428113a454b0207e42f339f.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1647655526&t=b3d3a0e7fcd9e780f7d6b7522f2ac482"];

        var btn = document.querySelector("button");
        var imgContainerEle = document.querySelector(".imgContainer");
        var chioseKey = -1;  //保存上次随机出来的图片的索引值
        btn.onclick = function(){
            var key = randomNum(0,imgArr.length-1);
            while(chioseKey==key){  // 会用这个随机出来的索引和上次的比较 如果一样 那么继续随机 ，如果不同那么就接续随机key值。 一定可以保证这个随机的数和上次保存的不同；
                key = randomNum(0,imgArr.length-1);
            }
            chioseKey = key;  // 把这次随机的key再保存下来；
            console.log(key);
            imgContainerEle.style.backgroundImage = `url(${imgArr[key]})`;
        }



        function randomNum(min,max){
            return parseInt(Math.random()*(max+1-min)) +min
        }

    //    console.log(  randomNum(0,3));

    </script>
</body>
</html>